﻿using System.Web.Mvc;
using System.Web.Security;
using EnetaMvc.ApplicationServices;
using EnetaMvc.Web.Models;
using EnetaMvc.Web.Security;
using log4net;

namespace EnetaMvc.Web.Controllers
{
    public class HomeController : BaseController
    {
        private readonly INewsService _newsService;
        private readonly IUserService _userService;
        private readonly IFileService _fileService;
        private readonly IForumService _forumService;
        private readonly IContentService _contentService;
        private readonly ILog _logger;

        public HomeController(INewsService newsService, IUserService userService, IFileService fileService, IForumService forumService, IContentService contentService, ILog logger)
        {
            _newsService = newsService;
            _userService = userService;
            _fileService = fileService;
            _logger = logger;
            _contentService = contentService;
            _forumService = forumService;
        }

        [HttpGet]
        public ActionResult Index()
        {
            var model = new FrontPageModel();
            model.BlogPosts = _newsService.ListPublishedBlogPosts(1, 12).Results;
            model.Articles = _newsService.ListPublishedArticles(1, 6).Results;
            model.LastForumPosts = _forumService.ListLastTopicsOverForums();
            return View(model);
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            Response.Write(filterContext.Exception);
            Response.End();
        }

        [HttpGet]
        public ActionResult Register()
        {
            if (Session["Token"] == null)
                return Redirect(Url.Content("~/login"));

            return View(new RegisterModel());
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var token = (string)Session["Token"];
            var result = _userService.RegisterUser(model.UserName, model.Email, token);
            if(!result.IsValid())
            {
                CopyErrorsToModelState(result.Results);
                return View(model);
            }

            InitializeSession(token);

            return Redirect(Url.Content("~/Profiles/Edit"));
        }

        [HttpPost]
        public ActionResult Index(string appctx)
        {
            var wll = new WindowsLiveLogin(true);
            var liveUser = wll.ProcessLogin(Request.Form);

            Session["Token"] = liveUser.Id;

            if (_userService.UserTokenExists(liveUser.Id))
            {
                InitializeSession(liveUser.Id);
                var redirectUrl = Request["appctx"];
                if (!string.IsNullOrEmpty(redirectUrl))
                    return Redirect(redirectUrl);

                return Redirect(Url.Content("~/"));
            }
            return Redirect(Url.Content("~/register"));
        }
        
        [NonAction]
        private void InitializeSession(string token)
        {
            var user = _userService.GetUserByToken(token);
            Session["UserId"] = user.Id;
            Session["UserName"] = user.UserName;

            if (Membership.ValidateUser(token, "asdasdkpaskdo"))
            {
                FormsAuthentication.SetAuthCookie(token, false);
            }
        }

        public ActionResult LogIn()
        {
            string redirectUrl = AuthConfig.LiveLoginUrl + Server.UrlEncode(Url.Content("~/"));

            if (Request.QueryString["ReturnUrl"] != null)
            {
                redirectUrl = AuthConfig.LiveLoginUrl + Server.UrlEncode(Request.QueryString["ReturnUrl"]);
            }
            else if (Request.UrlReferrer != null)
            {
                redirectUrl = AuthConfig.LiveLoginUrl + Server.UrlEncode(Request.UrlReferrer.ToString());
            }

            return Redirect(redirectUrl);
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            Session.Remove("Token");

            return Redirect(Url.Content("~/"));
        }
    }
}
